<?php
namespace  app\admin\controller;
use think\Db;
use think\Controller;
use think\Session;
use think\Request;
use app\admin\controller\Base;
class Partners extends Base
{
    // 合伙人类型展示
    public function classindex(Request $request){
        if ($request->isAjax()) {
            $page       = input('get.page');
            $limit      = input('get.limit');
            $count  = DB::name('partner_class')->count();
            $lists  = DB::name('partner_class')->field('class_id,class_name,class_jifen,class_money,class_edit_time')->page($page,$limit)
                    ->select();
            $return = [
                    "code"      => 220,
                    "msg"       => "",
                    "count"     => $count,
                    "data"      => $lists,
                ];
            return json($return);
        }else{
            return view();
        }
    }

    // 合伙人类型编辑
    public function classedit(Request $request){
        extract (input());
        if ($request->isAjax()) {
            // $post = $request->post();
            // $res['class_name']          = $post['class_name'];
            // $res['class_money']         = $post['class_money'];
            // $res['class_jifen']         = $post['class_jifen'];
            // $res['class_only_rate']     = $post['class_only_rate'];
            // // 事业合伙人存储
            // // if ($post['class_level'] == 2) {
            // //     $res['class_num']           = $post['class_num'];
            // //     $res['class_tui_money']     = $post['class_tui_money'];
            // // }
            // // 城市合伙人存储
            // if ($post['class_level'] == 3 || $post['class_level'] == 2) {
                // $res['class_num']           = $post['class_num'];
            // }
            // $res['class_tui_money']     = $post['class_tui_money'];
            // $res['class_info']           = $post['html'];
            // $res['class_fans_days']      = $post['class_fans_days'];
            // $res['class_fans_jifen']     = $post['class_fans_jifen'];
            // $res['class_fans_jifen_reg'] = $post['class_fans_jifen_reg'];
            // $res['class_fans_jifen_edi'] = $post['class_fans_jifen_edi'];
            // $res['class_tui_jifen']      = $post['class_tui_jifen'];
            // $res['class_agent_money']    = $post['class_agent_money'];
            // $res['class_head_money']     = $post['class_head_money'];
            // $res['class_edit_time']      = date('Y-m-d H:i:s',time());
            // $re = DB::name('partner_class')
                // ->where(['class_id'=>$post['class_id']])
                // ->update($res);
            // if (!empty($re)) {
                // return json(['code'=>200,'msg'=>'保存成功！']);
            // }else{
                // return json(['code'=>300,'msg'=>'保存失败！']);
            // }
        }else{
            $data  = DB::name('partner_class')
                    ->where(['class_id'=>$class_id])
                    ->find();
            $this->assign('data',$data);
            return view();
        }
    }

    // 合伙人列表
    public function index(Request $request){
        if ($request->isAjax()) {
            extract (input ());
            $where = array();
            if(session ('area')){
                $where['par_qu_id'] = ['in',session('area')];
            }else{
                if(isset($role)&&$role != ""){
                    $where['par.par_qu_id'] = ['like',"%".$role."%"];
                }
            }
            if (isset($key)&&$key != '') {
                $where['u.user_phone'] = ['like',"%".$key."%"];
            }
            if (isset($user_m_open)&&$user_m_open != '') {
                $where['u.user_m_open'] = $user_m_open;
            }
            $page       = input('get.page');
            $limit      = input('get.limit');
            $field = 'par.*,a.district,u.user_image,u.user_partner_type,u.user_username,u.user_phone,u.user_balance,u.user_balance_yet,u.user_money_balance,u.user_money_balance_yet';
            $field .= ',u.user_m_open,user_m_open_time,user_m_pool_money';
            $partners   = DB::name('partner')->alias('par')
                        ->join('area a','par.par_qu_id = a.district_id')
                        ->join('u_user u','par.par_user_id = u.user_id')
                        ->where(['par_cancel'=>0])
                        ->where($where)
                        ->page($page,$limit)
                        ->field($field)
                        ->order('par_add_time desc')
                        ->select();
            $count      = DB::name('partner')->alias('par')
                        ->join('area a','par.par_qu_id = a.district_id')
                        ->join('u_user u','par.par_user_id = u.user_id')
                        ->where(['par_cancel'=>0])
                        ->where($where)
                        ->count();
            if (!empty($partners)) {
                // 父级合伙人
                foreach ($partners as $key => $vo) {
                    $partner_parent = DB::name('partner')->alias('par')
                                    ->where(['par_id'=>$vo['par_parent_id']])
                                    ->join('u_user u','u.user_id = par.par_user_id')
                                    ->field('par_id as partner_parent_id,par_user_username,par_user_phone,user_username,user_phone,user_balance,user_balance_yet,user_money_balance,user_money_balance_yet')
                                    ->find();
                    if (!empty($partner_parent)) {
                        $partners[$key]['partner_parent_name']  = $partner_parent['user_username'];
                        $partners[$key]['partner_parent_phone'] = $partner_parent['user_phone'];
                    }else{
                        $partners[$key]['partner_parent_name']  = '';
                        $partners[$key]['partner_parent_phone'] = '';
                    }
                    // 是否开店
                    $shop_name = DB::name('shop')->where(['shop_user_id'=>$vo['par_user_id']])->value('shop_name');
                    if (!empty($shop_name)) {
                        $partners[$key]['shop_name'] = $shop_name;
                    }else{
                        $partners[$key]['shop_name'] = '';
                    }
                    // 收益 = user_balance + user_money_balance
                    $partners[$key]['total_balance'] = $vo['user_balance'] + $vo['user_money_balance'];
                    //产品池
                    $partners[$key]['user_m_open2'] = $vo['user_m_open'];
                    if($vo['user_m_open'] == 1){
                        $partners[$key]['user_m_open'] = '没有开启';
                        $partners[$key]['user_m_open_time'] = '--';
                    }else{
                        $partners[$key]['user_m_open'] = '已开启';
                    }
                }
            }
            $return = [
                    "code"      => 220,
                    "msg"       => "",
                    "count"     => $count,
                    "data"      => $partners,
                ];
            return json($return);
        }else{
            $partneradd = array();
            //今天开始时间
            $beginToday     = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y')));
            //今天结束时间
            $endToday       = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);
            //昨天开始时间
            $beginYesterday = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')-1,date('Y')));
            //昨天结束时间
            $endYesterday   = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))-1);
            //本月开始时间
            $beginThismonth = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),1,date('Y')));
            //本月结束时间
            $endThismonth   = date("Y-m-d H:i:s",mktime(23,59,59,date('m'),date('t'),date('Y')));
            //上月开始时间
            $beginLastmonth = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
            //上月结束时间
            $endLastmonth   = date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y")));
            // 今日新增
            $today_tui_num  = $this->partner_add_num(1,0,$beginToday,$endToday);
            $today_shi_num  = $this->partner_add_num(2,0,$beginToday,$endToday);
            $today_city_num = $this->partner_add_num(3,0,$beginToday,$endToday);
            $today_num = $today_tui_num + $today_shi_num + $today_city_num;
            // 昨日新增
            $yesterday_tui_num  = $this->partner_add_num(1,0,$beginYesterday,$endYesterday);
            $yesterday_shi_num  = $this->partner_add_num(2,0,$beginYesterday,$endYesterday);
            $yesterday_city_num = $this->partner_add_num(3,0,$beginYesterday,$endYesterday);
            $yesterday_num = $yesterday_tui_num + $yesterday_shi_num + $yesterday_city_num;
            // 本月新增
            $thismonth_tui_num  = $this->partner_add_num(1,0,$beginThismonth,$endThismonth);
            $thismonth_shi_num  = $this->partner_add_num(2,0,$beginThismonth,$endThismonth);
            $thismonth_city_num = $this->partner_add_num(3,0,$beginThismonth,$endThismonth);
            $thismonth_num = $thismonth_tui_num + $thismonth_shi_num + $thismonth_city_num;
            // 本月新增
            $lastmonth_tui_num  = $this->partner_add_num(1,0,$beginLastmonth,$endLastmonth);
            $lastmonth_shi_num  = $this->partner_add_num(2,0,$beginLastmonth,$endLastmonth);
            $lastmonth_city_num = $this->partner_add_num(3,0,$beginLastmonth,$endLastmonth);
            $lastmonth_num = $lastmonth_tui_num + $lastmonth_shi_num + $lastmonth_city_num;
            $partneradd['today_tui_num']    = $today_tui_num;
            $partneradd['today_shi_num']    = $today_shi_num;
            $partneradd['today_city_num']   = $today_city_num;
            $partneradd['today_num']        = $today_num;
            $partneradd['yesterday_tui_num']  = $yesterday_tui_num;
            $partneradd['yesterday_shi_num']  = $yesterday_shi_num;
            $partneradd['yesterday_city_num'] = $yesterday_city_num;
            $partneradd['yesterday_num']      = $yesterday_num;
            $partneradd['thismonth_tui_num']  = $thismonth_tui_num;
            $partneradd['thismonth_shi_num']  = $thismonth_shi_num;
            $partneradd['thismonth_city_num'] = $thismonth_city_num;
            $partneradd['thismonth_num']      = $thismonth_num;
            $partneradd['lastmonth_tui_num']  = $lastmonth_tui_num;
            $partneradd['lastmonth_shi_num']  = $lastmonth_shi_num;
            $partneradd['lastmonth_city_num'] = $lastmonth_city_num;
            $partneradd['lastmonth_num']      = $lastmonth_num;
            // 合伙人城市
            $partner_city = array();
            $partner_city_area   = DB::name('partner')->where(['par_cancel'=>0])->column('par_qu_id');
            if (!empty($partner_city_area)) {
                $partner_city   = DB::name('area')
                                ->where(['district_id'=>['in',$partner_city_area]])
                                ->field('district_id,district')
                                ->select();
            }
            if(session ('area')){
                $qu = 1;
            }else{
                $qu = 0;
            }
            $this->assign('partner_city',$partner_city);
            $this->assign('partneradd',$partneradd);
            $this->assign('qu',$qu);
            return view();
        }
    }

    // 当天，昨天，当月，上月新增合伙人人数
    public function seeInfo(){
        $order = Db::table('up_u_user')
            ->where('user_id',input('user_id'))
            ->find();
        return $this->fetch('partners/seeinfo',['data'=>$order]);
    }
    // 当天，昨天，当月，上月新增合伙人人数
    public function partner_add_num($class_level, $cancel=0, $begin, $end){
        if(session ('area')){
            $where['par_qu_id'] = ['in',session('area')];
        }
        $where['par_class_level']   = $class_level;
        $where['par_cancel']        = $cancel;
        $where['par_add_time']      = ['between',[$begin,$end]];
        $add_num    = DB::name('partner')
                    ->where($where)
                    ->count();
        return $add_num;
    }

    // 分销合伙人下级
    public function partnerchild(Request $request){
        if ($request->isAjax()) {
            extract (input ());
            $where = array();
            if (isset($key)&&$key != '') {
                $where['par.par_user_phone'] = ['like',"%".$key."%"];
            }
            $where['par_parent_id'] = $par_id;
            $page       = input('get.page');
            $limit      = input('get.limit');
            $partners   = DB::name('partner')->alias('par')
                        ->join('area a','par.par_qu_id = a.district_id')
                        ->join('u_user u','par.par_user_id = u.user_id')
                        ->where(['par_cancel'=>0])
                        ->where($where)
                        ->page($page,$limit)
                        ->field('par.*,a.district,u.user_image,u.user_partner_type,u.user_username,u.user_phone,u.user_balance,user_balance_yet,user_money_balance,user_money_balance_yet')
                        ->select();
            $count      = DB::name('partner')->alias('par')
                        ->join('area a','par.par_qu_id = a.district_id')
                        ->join('u_user u','par.par_user_id = u.user_id')
                        ->where(['par_cancel'=>0])
                        ->where($where)
                        ->count();
            foreach ($partners as $key => $vo) {
                $partners[$key]['total_balance'] = $vo['user_balance'] + $vo['user_money_balance'];
            }
            $return = [
                    "code"      => 220,
                    "msg"       => "",
                    "count"     => $count,
                    "data"      => $partners,
                ];
            return json($return);
        }else{
            $par_id = $request->get('par_id');
            $this->assign('par_id',$par_id);
            return view();
        }
    }

    // 合伙人收益详情
    public function earnings(Request $request){
        extract (input());
        if($request->isAjax ()){
            extract (input());
            $par_user_id = DB::name('partner')->where(['par_id'=>$par_id])->value('par_user_id');
            $map['m_user_id'] = $par_user_id;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('earnings e')
                ->join('u_user u','e.m_user_id = u.user_id','left')
                ->where($map)
                ->count();
            $lists = Db::name('earnings e')
                ->join('u_user u','e.m_user_id = u.user_id','left')
                ->field('m_user_id,m_add_time,m_money,m_from_shop,user_username')
                ->where($map)
                ->page($Nowpage,$limits)
                ->order ('m_add_time desc')
                ->select ();
            foreach ($lists as $key => $vo) {
                if (!empty($vo['m_from_shop'])) {
                    $lists[$key]['type'] = '提成收益';
                }else{
                    $lists[$key]['type'] = '分红收益';
                }
            }
            // 邀请获得的现金
            $count1 = DB::name('partner_invite i')
                    ->join('u_user u','i.inv_user_id = u.user_id','left')
                    ->where(['inv_par_id'=>$par_id,'inv_money'=>['<>','']])
                    ->count();
            $invite = DB::name('partner_invite i')
                    ->join('u_user u','i.inv_user_id = u.user_id','left')
                    ->where(['inv_par_id'=>$par_id,'inv_money'=>['<>','']])
                    ->field('inv_user_id as m_user_id,inv_money as m_money,inv_add_time as m_add_time,inv_be_userid as m_from_shop,user_username')
                    ->order('inv_add_time desc')
                    ->page($Nowpage,$limits)
                    ->select();
            foreach ($invite as $key => $vo) {
                $invite[$key]['type'] = '推荐收益';
            }
            $lists = array_merge($lists,$invite);
            $count = $count + $count1;
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }else{
            $par_id = $request->get('par_id');
            $this->assign('par_id',$par_id);
            return view();
        }
    }

    // 代理商收益
    public function agentmoney(Request $request){
        if ($request->isAjax()) {
            extract (input());
            if (session('area')) {
                $where['m_area'] = session('area');
            }else{
                if(isset($role)&&$role != ""){
                    $where['e.m_area'] = ['like',"%".$role."%"];
                }
            }
            $where['m_area_type'] = 2;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('earnings e')
                ->join('u_user u','e.m_area_user = u.user_id')
                ->join('area a','e.m_area = a.district_id')
                ->where($where)
                ->count();
            $lists = Db::name('earnings e')
                ->join('u_user u','e.m_area_user = u.user_id')
                ->join('area a','e.m_area = a.district_id')
                ->field('e.*,user_username,user_level,district,user_phone')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order ('m_add_time desc')
                ->select ();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }else{
            $area = Db::name('earnings')->where(['m_area_type'=>2])->column('m_area');
            if (session('area')) {
                $where1['m_area'] = session('area');
            }
            $where1['m_area_type'] = 2;
            $where1['m_area_user'] = ['<>',''];
            $moneys = Db::name('earnings')->where($where1)->sum('m_money');
            if (!empty($area)) {
                $agent_city   = DB::name('area')
                                ->where(['district_id'=>['in',$area]])
                                ->field('district_id,district')
                                ->select();
            }
            if(session ('area')){
                $qu = 1;
            }else{
                $qu = 0;
            }
            $this->assign('qu',$qu);
            $this->assign('agent_city',$agent_city);
            $this->assign('moneys',$moneys);
            return view();
        }
    }

    // 总部收益
    public function headmoney(Request $request){
        if ($request->isAjax()) {
            extract (input());
            $where['m_area_type'] = 1;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('earnings e')
                ->join('u_user u','e.m_area_user = u.user_id')
                ->where($where)
                ->count();
            $lists = Db::name('earnings e')
                ->join('u_user u','e.m_area_user = u.user_id')
                ->field('e.*,user_username,user_level,user_phone')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order ('m_add_time desc')
                ->select ();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }else{
            $where1['m_area_type'] = 1;
            $where1['m_area_user'] = ['<>',''];
            $moneys = Db::name('earnings')->where($where1)->sum('m_money');
            $this->assign('moneys',$moneys);
            return view();
        }
    }
}